﻿using System;
using System.Management;
using System.Management.Automation;
using System.IO;
using System.Net;
using Microsoft.SharePoint;

namespace SPPoSh.Cmdlets.Artefacts.Files
{
    [Cmdlet(VerbsCommon.Copy, "SPFile")]
    class CopySPFileCmdlet : Cmdlet
    {
        [Parameter(Position = 0, Mandatory = true, HelpMessage = "URL of the source document")]
        public string SourceDocumentURL;

        [Parameter(Position = 1, Mandatory = true, HelpMessage = "URL of the destination document")]
        public string DestinationDocumentURL;

        protected override void ProcessRecord()
        {
            Stream sourceStream;
            using (SPSite site = new SPSite(SourceDocumentURL))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPFile sourceFile = web.GetFile(SourceDocumentURL);
                    sourceStream = sourceFile.OpenBinaryStream();
                    this.WriteDebug("Obtained stream");
                    using (SPSite siteDest = new SPSite(DestinationDocumentURL))
                    {
                        using (SPWeb webDest = siteDest.OpenWeb())
                        {
                            string[] paths = DestinationDocumentURL.Split('/');
                            string fileName = paths[paths.Length - 1];
                            string libraryUrl = DestinationDocumentURL.Replace(fileName, "");
                            SPList docLib = webDest.GetList(libraryUrl);
                            SPFolder libFolder = webDest.Folders[docLib.Title];
                            libFolder.Files.Add(DestinationDocumentURL, sourceStream);
                        }
                    }
                }
            }                   
        }
    }
}
